package systemController

import (
	"net/http"
	"wisdomCoach/global"
	"wisdomCoach/model"
	"wisdomCoach/utils"

	"github.com/gin-gonic/gin"
)

type RequestUser struct {
	UserName string `json:"userName"`
	Password string `json:"password"`
}

func Register(cxt *gin.Context) {
	var (
		user     model.User
		register RequestUser
	)
	if err := cxt.ShouldBindJSON(&register); err != nil {
		cxt.JSON(http.StatusBadRequest, gin.H{
			"error": "请求数据有误",
		})
		return
	}

	err := global.DB.Where("user_name = ?", register.UserName).First(&user).Error
	if err == nil {
		cxt.JSON(http.StatusForbidden, gin.H{
			"error": "该用户已存在",
		})
		return
	}

	password, err := utils.EncryptPassword(register.Password)
	if err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	user.UserName = register.UserName
	user.Password = password

	result := global.DB.Create(&user)
	if result.Error != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	token, err := utils.CreateToken(result.RowsAffected, user.UserName)
	if err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}

	cxt.JSON(http.StatusOK, gin.H{
		"code":  200,
		"token": token,
		"msg":   "操作成功",
	})
}
